package controller;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author zhangyanqi
 * @since 1.0 2017/12/3
 */
public class ChattingRoomConfig extends ServerEndpointConfig.Configurator {

    private String origin;

    public ChattingRoomConfig() {
        InputStream inputStream = this.getClass().getResourceAsStream("/config.properties");
        if (inputStream == null) {
            throw new RuntimeException("没有找到资源");
        }
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件失败");
        }
        origin = properties.getProperty("origin");
        System.out.println("加载origin:" + origin);
    }


    @Override
    public boolean checkOrigin(String originHeaderValue) {
        if (!originHeaderValue.equals(origin)) {
            return false;
        }
        return super.checkOrigin(originHeaderValue);
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession session = (HttpSession) request.getHttpSession();
        //获得sessoion之后可以进行权限的判断，没有权限的话拒绝进行连接
        if (session != null) {
            sec.getUserProperties().put(HttpSession.class.getName(), session);
        } else {
        }
    }
}
